﻿using System;
using Microsoft.Win32;

namespace Commands.Settings
{
    class ProgrammsFinder
    {
        public static string GetTeamViewerPathFromRegistry()
        {
            var settingsPath = SettingsHelper.Settings.ProgrammsPaths.Teamviewer;

            if (settingsPath != null)
                return settingsPath;

            var key = (string)Registry.GetValue(
                @"HKEY_CLASSES_ROOT\TeamViewerConfiguration\shell\open\command", "", null);

            return _GetPathFromString(key);
        }

        public static string GetTorrentClientPath()
        {
            var settingsPath = SettingsHelper.Settings.ProgrammsPaths.TorrentClient;

            if (!string.IsNullOrEmpty((settingsPath)))
                return settingsPath;

            var key = (string)Registry.GetValue(@"HKEY_CLASSES_ROOT\uTorrent\shell\open\command", "", null) ??
                      (string)Registry.GetValue(@"HKEY_CLASSES_ROOT\BitTorrent\shell\open\command", "", null);

            return _GetPathFromString(key);
        }

        private static string _GetPathFromString(string key)
        {
            if (key == null || !key.Contains("%1"))
                return key;

            var index = key.LastIndexOf(" ");

            return key.Substring(0, index);
        }
    }
}
